package com.mantru.iotpot.Adapter

import android.annotation.SuppressLint
import android.app.Activity
import android.content.Context
import android.util.Log
import android.widget.TextView
import android.widget.Toast
import androidx.core.content.ContextCompat
import com.mantru.iotpot.Adapter.Base.AppAdapter
import com.mantru.iotpot.Adapter.Base.AppHolder
import com.mantru.iotpot.Bean.DishesChooseBean
import com.mantru.iotpot.R

class DishesChooseAdapter(var context: Context, layoutResId: Int, var data: MutableList<DishesChooseBean>): AppAdapter<DishesChooseBean>(context, layoutResId, data) {

    private var dishesChooseListener: DishesChooseListener? = null
    fun setDishesChooseListener(dishesChooseListener: DishesChooseListener?) {
        this.dishesChooseListener = dishesChooseListener
    }
    interface DishesChooseListener {
        fun onChoose(position: Int)
    }
    
    override fun convert(holder: AppHolder?, position: Int, item: DishesChooseBean) {
        val textView: TextView? = holder?.getView<TextView>(R.id.adapter_dishes_choose_text)
        holder?.setText(R.id.adapter_dishes_choose_text, item.name)
            ?.setOnClickListener(R.id.adapter_dishes_choose_text){
                if ( !item.isSelected ){
                    for (i in 0 until data.size) {
                        data[i].isSelected = false
                    }
                }
                // 切换选择状态
                item.isSelected = !item.isSelected
                dishesChooseListener!!.onChoose(position)
            }
        // 根据选择状态设置背景
        if (item.isSelected) {
            textView!!.setBackgroundResource(R.drawable.radius40_1151e4)
        } else {
            textView!!.setBackgroundResource(R.drawable.radius40_16ffffff)
        }
    }

    @SuppressLint("NotifyDataSetChanged")
    //刷新数据
    fun updateData(newData: List<DishesChooseBean>) {
        (context as? Activity)?.runOnUiThread {
            (mItems as? MutableList)?.apply {
                clear()
                addAll(newData)
            }
            notifyDataSetChanged()
        }
    }
}